//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "aisuppress\fn_bulletHandler.sqf"
#include <core_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private "_unit";
DEFAULT_PARAM(_unit,0,objNull);

if (!isNil "_unit" && {IS_OBJECT(_unit)} && {!isNull _unit} && {local _unit} && {alive _unit} && {!isPlayer _unit}) then {
	TRACE_1("Local Unit",ARR_3(_unit, typeOf _unit, local _unit));
	private ["_shooter","_bullet","_bpos","_start_pos","_start_time","_proximity","_last_bullet","_time_diff","_bullet_count","_idx"];
	DEFAULT_PARAM(_shooter,1,objNull);
	DEFAULT_PARAM(_bullet,2,objNull);
	DEFAULT_PARAM(_bpos,3,ARR_3(0,0,0));
	DEFAULT_PARAM(_start_pos,4,ARR_3(0,0,0));
	DEFAULT_PARAM(_start_time,5,0);
	
	if (!isNull _shooter) then {
		_proximity = _bpos distance _unit;
		if (_proximity <= GVAR(MAX_BULLET_DIST_FOR_SUPP)) then {
			_last_bullet = _unit getVariable [QGVAR(LAST_BULLET),0];
			_time_diff = time - _last_bullet;	
			if (_time_diff > GVAR(BULLETS_REMEMBER_TIMEOUT)) then {
				_unit setVariable [QGVAR(FIRST_BULLET),time];
			};
			_unit setVariable [QGVAR(LAST_BULLET),time];
			_bullet_count = _unit getVariable [QGVAR(BULLET_COUNT),0];
			if (_time_diff < GVAR(MAX_TIME_BETWEEN_BULLETS)) then {
				INC(_bullet_count);
			} else {
				_bullet_count = 1;
			};
			
			_idx = _unit addEventHandler ["fired",FUNC(fires)];
			_unit setVariable [QGVAR(FIRED_EVT),_idx];
			
			_unit setVariable [QGVAR(BULLET_COUNT),_bullet_count];
			if (_bullet_count >= GVAR(MIN_BULLET_FOR_SUPP)) then {
				TRACE_1("Suppressed",ARR_3(_unit,_time_diff,_bullet_count));
				if !(_unit in GVAR(AI_SUPPRESSION_LIST)) then {
					_unit setVariable [QGVAR(LAST_SHOOTER),_shooter];
					_unit addEventHandler ["killed",FUNC(alertGroup)];
					GVAR(AI_SUPPRESSION_LIST) set [count GVAR(AI_SUPPRESSION_LIST), _unit];
					TRACE_1("Queued",ARR_3(_unit,_time_diff,_bullet_count));
				};
			} else {
				TRACE_1("Updated",ARR_3(_unit,_time_diff,_bullet_count));
			};
		};
	};
} else {
	TRACE("Not for me!");
};

TRACE("End");
TMFPROFILERSTOP;